package com.cgbl.cg.ui.login

import android.content.Intent
import android.content.pm.ActivityInfo
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.StringUtils
import com.cgbl.cg.BR
import com.cgbl.cg.BuildConfig
import com.cgbl.cg.R
import com.cgbl.cg.databinding.AppActivityLoginCodeBinding
import com.cgbl.cg.vm.login.LoginCodeViewModel
import com.mobile.auth.gatewayauth.*
import com.mobile.auth.gatewayauth.model.TokenRet
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate
import com.robot.base.base.activity.GLBaseActivity
import com.robot.base.configs.AppConstants
import com.robot.base.util.ToastUtils
import com.umeng.socialize.UMAuthListener
import com.umeng.socialize.UMShareAPI
import com.umeng.socialize.UMShareConfig
import com.umeng.socialize.bean.SHARE_MEDIA
import org.json.JSONException
import org.json.JSONObject

@Route(path = AppConstants.Router.Login.A_LOGIN_CODE)
class LoginCodeActivity : GLBaseActivity<AppActivityLoginCodeBinding, LoginCodeViewModel>() {
    private var mPhoneNumberAuthHelper: PhoneNumberAuthHelper? = null
    private var mTokenResultListener: TokenResultListener? = null
    override fun initContentView(savedInstanceState: Bundle?): Int =
        R.layout.app_activity_login_code

    override fun initVariableId(): Int = BR.viewModel

    override fun initComponents() {
        addSingleTitleBar("")
        sdkInit(BuildConfig.AUTH_SECRET)
        oneKeyLogin()
        setViewData()
        initLive()
        configAuthPage()
    }

    private fun setViewData() {
//        binding.tvPrompt.text = StringUtils.getString(R.string.app_en_tips_7)
        SpanUtils.with(binding.tvPrompt)
            .append(StringUtils.getString(R.string.app_en_tips_5))
            .append(StringUtils.getString(R.string.app_en_tips_6))
//            .setForegroundColor(Color.RED)
            .setClickSpan(resources.getColor(R.color.app_286FFF), false) {
                ToastUtils.showShort("点击了用户协议")
            }
            .append(StringUtils.getString(R.string.app_en_tips_8))
            .setForegroundColor(resources.getColor(R.color.app_286FFF))
//            .setQuoteColor(Color.RED)
            .append(StringUtils.getString(R.string.app_en_tips_9))
            .setClickSpan(resources.getColor(R.color.app_286FFF), false) {
                ToastUtils.showShort("点击了隐私协议")
            }
            .create()
    }

    private fun initLive() {
        viewModel.toLoginType.observe(this, Observer {
            it ?: return@Observer
            toWx(it)
        })

        viewModel.closeAuthEvent.observe(this){
            mPhoneNumberAuthHelper?.quitLoginPage()
        }
    }

    private fun toWx(type: SHARE_MEDIA) {
        if (!UMShareAPI.get(this).isInstall(this, type)) {
            ToastUtils.showShort(
                "${
                    when (type) {
                        SHARE_MEDIA.QQ -> {
                            StringUtils.getString(R.string.app_error_11)
                        }
                        SHARE_MEDIA.WEIXIN -> {
                            StringUtils.getString(R.string.app_error_10)
                        }
                        SHARE_MEDIA.SINA -> {
                            StringUtils.getString(R.string.app_error_12)
                        }
                        else -> {
                            ""
                        }
                    }
                }"
            )
            return
        }
        val config = UMShareConfig()
        config.isNeedAuthOnGetUserInfo(true)
        UMShareAPI.get(this).setShareConfig(config)
        UMShareAPI.get(this)
            .getPlatformInfo(this, type, object : UMAuthListener {
                override fun onStart(p0: SHARE_MEDIA?) {
                    LogUtils.e(p0)
                }

                override fun onComplete(
                    p0: SHARE_MEDIA?,
                    p1: Int,
                    p2: MutableMap<String, String>?
                ) {
                    when (type) {
                        SHARE_MEDIA.SINA -> {
                            p2?.get("uid")?.let {
                                LogUtils.e(it)

                            }
                        }
                        SHARE_MEDIA.WEIXIN, SHARE_MEDIA.QQ -> {
                            p2?.get("openid")?.let {
                                viewModel.weChatLogin(
                                    if (type == SHARE_MEDIA.WEIXIN) {
                                        "31"
                                    } else {
                                        "34"
                                    }, it, p2["iconurl"] ?: "", p2["name"] ?: ""
                                )
                            }
                        }
                    }
                }

                override fun onError(p0: SHARE_MEDIA?, p1: Int, p2: Throwable?) {
                    LogUtils.e(p0, p1, p2)
                    ToastUtils.showShort(p2?.message ?: "")
                }

                override fun onCancel(p0: SHARE_MEDIA?, p1: Int) {
                    LogUtils.e(p0, p1)
                }
            })
    }


    fun sdkInit(secretInfo: String?) {
        mTokenResultListener = object : TokenResultListener {
            override fun onTokenSuccess(s: String) {
                LogUtils.e("获取token成功：$s")
                mPhoneNumberAuthHelper?.hideLoginLoading()

                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS == tokenRet.code) {
                        Log.i("TAG", "唤起授权页成功：$s")
                    }
                    if (ResultCode.CODE_SUCCESS == tokenRet.code) {
                        Log.i("TAG", "获取token成功：$s")
//                        mPhoneNumberAuthHelper?.quitLoginPage()
//                        getResultWithToken(tokenRet.token)
                        viewModel.tokenPhone(tokenRet.token)
                        mPhoneNumberAuthHelper?.setAuthListener(null)
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }

            override fun onTokenFailed(s: String) {
                LogUtils.e("获取token失败：$s")
                mPhoneNumberAuthHelper?.hideLoginLoading()
                var tokenRet: TokenRet? = null
                try {
                    tokenRet = TokenRet.fromJson(s)
                    if (ResultCode.CODE_ERROR_USER_CANCEL == tokenRet?.code) {
                        //模拟的是必须登录 否则直接退出app的场景
                        finish()
                    } else {
                        showToast("一键登录失败切换到其他登录方式")
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
                mPhoneNumberAuthHelper?.quitLoginPage()
                mPhoneNumberAuthHelper?.setAuthListener(null)
            }
        }
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenResultListener)
        mPhoneNumberAuthHelper?.reporter?.setLoggerEnable(true)
        mPhoneNumberAuthHelper?.setAuthSDKInfo(secretInfo)
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private fun oneKeyLogin() {
        mPhoneNumberAuthHelper =
            PhoneNumberAuthHelper.getInstance(applicationContext, mTokenResultListener)
        mPhoneNumberAuthHelper?.checkEnvAvailable()
//        mUIConfig.configAuthPage()
        //用户控制返回键及左上角返回按钮效果
        mPhoneNumberAuthHelper?.userControlAuthPageCancel()
        //用户禁用utdid
        //mPhoneNumberAuthHelper.prohibitUseUtdid();
        //授权页是否跟随系统深色模式
        mPhoneNumberAuthHelper?.setAuthPageUseDayLight(true)
        //授权页物理返回键禁用
        //mPhoneNumberAuthHelper.closeAuthPageReturnBack(true);
        //横屏水滴屏全屏适配
        mPhoneNumberAuthHelper?.keepAuthPageLandscapeFullSreen(true)
        //授权页扩大协议按钮选择范围至我已阅读并同意
        //mPhoneNumberAuthHelper.expandAuthPageCheckedScope(true);
        getLoginToken(5000)
    }

    /**
     * 拉起授权页
     * @param timeout 超时时间
     */
    fun getLoginToken(timeout: Int) {
        mPhoneNumberAuthHelper!!.getLoginToken(this, timeout)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data)
    }

    fun configAuthPage() {
        mPhoneNumberAuthHelper?.setUIClickListener(AuthUIControlClickListener { code, context, jsonString ->
            var jsonObj: JSONObject? = null
            try {
                if (!TextUtils.isEmpty(jsonString)) {
                    jsonObj = JSONObject(jsonString)
                }
            } catch (e: JSONException) {
                jsonObj = JSONObject()
            }
            when (code) {
                ResultCode.CODE_ERROR_USER_CANCEL -> {
//                    Log.e(FragmentActivity.TAG, "点击了授权页默认返回按钮")
                    mPhoneNumberAuthHelper?.quitLoginPage()
//                    mActivity.finish()
                }
                ResultCode.CODE_ERROR_USER_SWITCH -> {
//                    Log.e(FragmentActivity.TAG, "点击了授权页默认切换其他登录方式")
                }

                ResultCode.CODE_ERROR_USER_LOGIN_BTN -> {
//                    if (!jsonObj.optBoolean("isChecked")) {
//                        Toast.makeText(mContext, R.string.custom_toast, Toast.LENGTH_SHORT).show()
//                    }
                }

                ResultCode.CODE_ERROR_USER_CHECKBOX -> {
//                    Log.e(
//                        FragmentActivity.TAG,
//                        "checkbox状态变为" + jsonObj.optBoolean("isChecked")
//                    )
                }

                ResultCode.CODE_ERROR_USER_PROTOCOL_CONTROL -> {
//                    Log.e(
//                        FragmentActivity.TAG,
//                        "点击协议，" + "name: " + jsonObj.optString("name") + ", url: " + jsonObj.optString("url")
//                    )
                }
                ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYBTN -> {
//                    Log.e(
//                        FragmentActivity.TAG,
//                        "用户调用userControlAuthPageCancel后使用左上角返回按钮返回交由sdk接入方控制"
//                    )
                    mPhoneNumberAuthHelper?.quitLoginPage()
//                    mActivity.finish()
                }
                ResultCode.CODE_ERROR_USER_CONTROL_CANCEL_BYKEY -> {
//                    Log.e(FragmentActivity.TAG, "用户调用userControlAuthPageCancel后使用物理返回键返回交由sdk接入方控制")
                    mPhoneNumberAuthHelper?.quitLoginPage()
//                    mActivity.finish()
                }
                else -> {}
            }
        })
        mPhoneNumberAuthHelper?.removeAuthRegisterXmlConfig()
        mPhoneNumberAuthHelper?.removeAuthRegisterViewConfig()
        var authPageOrientation: Int = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT
        if (Build.VERSION.SDK_INT === 26) {
            authPageOrientation = ActivityInfo.SCREEN_ORIENTATION_BEHIND
        }
        mPhoneNumberAuthHelper?.addAuthRegisterXmlConfig(
            AuthRegisterXmlConfig.Builder()
                .setLayout(R.layout.app_activity_login, object : AbstractPnsViewDelegate() {
                    override fun onViewCreated(view: View?) {
                        findViewById(R.id.tv_back).setOnClickListener {
                            mPhoneNumberAuthHelper?.quitLoginPage()
                        }
                        findViewById(R.id.tv_3).setOnClickListener {
                            mPhoneNumberAuthHelper?.quitLoginPage()
                        }
                        
                        findViewById(R.id.iv_1).setOnClickListener { 
                            viewModel.toQqClick.execute()
                        }

                        findViewById(R.id.iv_2).setOnClickListener {
                            viewModel.toWxClick.execute()
                        }
                    }
                })
                .build()
        )
        mPhoneNumberAuthHelper?.setAuthUIConfig(
            AuthUIConfig.Builder()
                .setAppPrivacyOne("《用户服务协议》", "https://test.h5.app.tbmao.com/user")
                .setAppPrivacyTwo("《隐私政策》", "https://www.baidu.com")
                .setAppPrivacyColor(Color.GRAY, Color.parseColor("#286FFF"))
                .setNavHidden(true)
                .setLogoHidden(true)
                .setSloganHidden(true)
                .setSwitchAccHidden(true)
                .setPrivacyState(false)
                .setCheckboxHidden(false)
                .setUncheckedImgDrawable(getDrawable(R.mipmap.app_ic_un_check))
                .setCheckedImgDrawable(getDrawable(R.mipmap.app_ic_check))
                .setLightColor(true)
                .setWebViewStatusBarColor(Color.TRANSPARENT)
                .setStatusBarColor(Color.TRANSPARENT)
                .setStatusBarUIFlag(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
                .setWebNavTextSizeDp(20)
                .setNumberSizeDp(20)
                .setNumberColor(Color.BLACK)
                .setAuthPageActIn("in_activity", "out_activity")
                .setAuthPageActOut("in_activity", "out_activity")
                .setVendorPrivacyPrefix("《")
                .setVendorPrivacySuffix("》")
                .setPageBackgroundPath("page_background_color")
                .setLogBtnBackgroundPath("app_select_round_8_cc2d2d")
                .setLogBtnText("本机号码一键登录")
                .setLogBtnTextSizeDp(16)
                .setScreenOrientation(authPageOrientation)
                .create()
        )
    }
}